package com.cskaoyan.utils;

import com.mysql.jdbc.Driver;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * 创建日期: 2022/10/08 14:27
 *
 * @author ciggar
 *
 * 1. url,username,password 这些是写死的，可以使用配置文件来配置
 * 2. 把连接对象单例化
 * 3. 可以把注册驱动这一步解耦
 */
public class JDBCUtils {

    static Connection connection;

    // 读取配置文件
    static String url = null;
    static String username= null;
    static String password = null;
    static String driverClassName = null;

    static {

        try {




            Properties properties = new Properties();
            properties.load(new FileInputStream("jdbc.properties"));


            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            driverClassName = properties.getProperty("driver");



            // 注册驱动
            // DriverManager.registerDriver(new Driver());
            // new Driver()
            // Class.forName(driverClassName);



            // 获取连接 (返回的应该是接口的实现类的实例对象 )(com.mysql.jdbc.JDBC4Connection)
            connection = DriverManager.getConnection(url,username,password);


        }catch (Exception ex) {
            ex.printStackTrace();
        }

    }


    // 获取连接
    public static Connection getConnection(){

        return connection;
    }


    // 关闭资源
    public static void closeResource(ResultSet resultSet, Statement statement,Connection connection){

        try {
            if (resultSet != null) resultSet.close();
            if (statement != null) statement.close();
            if (connection != null) connection.close();
        }catch (Exception ex) {
            ex.printStackTrace();
        }

    }


    // 获取新的连接
    public static Connection getNewConnection(){


        // 注册驱动
        try {
            Class.forName(driverClassName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        Connection conn = null;
        // 获取连接 (返回的应该是接口的实现类的实例对象 )(com.mysql.jdbc.JDBC4Connection)
        try {
            conn = DriverManager.getConnection(url,username,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return  conn;


    }
}
